// 任务管理应用
class TaskManager {
    constructor() {
        this.tasks = JSON.parse(localStorage.getItem('tasks')) || [];
        this.currentFilter = 'all';
        this.initializeEventListeners();
        this.renderTasks();
    }

    initializeEventListeners() {
        // 表单提交事件
        document.getElementById('taskForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.addTask();
        });

        // 过滤器按钮事件
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.setFilter(e.target.dataset.filter);
            });
        });
    }

    addTask() {
        const title = document.getElementById('taskTitle').value;
        const description = document.getElementById('taskDescription').value;
        const priority = document.getElementById('taskPriority').value;
        const dueDate = document.getElementById('taskDueDate').value;

        const task = {
            id: Date.now(),
            title,
            description,
            priority,
            dueDate: dueDate || null,
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.tasks.unshift(task);
        this.saveTasks();
        this.renderTasks();
        this.resetForm();
    }

    editTask(id, updates) {
        const taskIndex = this.tasks.findIndex(task => task.id === id);
        if (taskIndex !== -1) {
            this.tasks[taskIndex] = { ...this.tasks[taskIndex], ...updates };
            this.saveTasks();
            this.renderTasks();
        }
    }

    deleteTask(id) {
        if (confirm('确定要删除这个任务吗？')) {
            this.tasks = this.tasks.filter(task => task.id !== id);
            this.saveTasks();
            this.renderTasks();
        }
    }

    toggleTaskCompletion(id) {
        const task = this.tasks.find(task => task.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
        }
    }

    setFilter(filter) {
        this.currentFilter = filter;
        
        // 更新活动按钮样式
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.filter === filter) {
                btn.classList.add('active');
            }
        });

        this.renderTasks();
    }

    getFilteredTasks() {
        switch (this.currentFilter) {
            case 'pending':
                return this.tasks.filter(task => !task.completed);
            case 'completed':
                return this.tasks.filter(task => task.completed);
            default:
                return this.tasks;
        }
    }

    renderTasks() {
        const container = document.getElementById('tasksContainer');
        const filteredTasks = this.getFilteredTasks();

        if (filteredTasks.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <p>暂无任务</p>
                    <small>添加您的第一个任务开始吧！</small>
                </div>
            `;
            return;
        }

        container.innerHTML = filteredTasks.map(task => `
            <div class="task-item ${task.completed ? 'task-completed' : ''}">
                <input type="checkbox" class="task-checkbox" 
                       ${task.completed ? 'checked' : ''} 
                       onchange="taskManager.toggleTaskCompletion(${task.id})">
                
                <div class="task-content">
                    <h3>${this.escapeHtml(task.title)}</h3>
                    ${task.description ? `<p>${this.escapeHtml(task.description)}</p>` : ''}
                    <div class="task-meta">
                        <span class="priority priority-${task.priority}">
                            ${this.getPriorityText(task.priority)}
                        </span>
                        ${task.dueDate ? `<span>截止: ${new Date(task.dueDate).toLocaleDateString()}</span>` : ''}
                    </div>
                </div>
                
                <div class="task-actions">
                    <button class="btn-edit" onclick="taskManager.promptEditTask(${task.id})">编辑</button>
                    <button class="btn-delete" onclick="taskManager.deleteTask(${task.id})">删除</button>
                </div>
            </div>
        `).join('');
    }

    promptEditTask(id) {
        const task = this.tasks.find(t => t.id === id);
        if (!task) return;

        const newTitle = prompt('编辑任务标题:', task.title);
        if (newTitle === null) return;

        const newDescription = prompt('编辑任务描述:', task.description);
        
        this.editTask(id, {
            title: newTitle || task.title,
            description: newDescription !== null ? newDescription : task.description
        });
    }

    resetForm() {
        document.getElementById('taskForm').reset();
    }

    saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(this.tasks));
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    getPriorityText(priority) {
        const texts = {
            'high': '高优先级',
            'medium': '中优先级',
            'low': '低优先级'
        };
        return texts[priority] || priority;
    }
}

// 初始化应用
const taskManager = new TaskManager();